package com.weixin.api.content.shiro;

import com.google.gson.Gson;
import com.weixin.common.ResponseResult;
import org.apache.shiro.web.filter.authc.AuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author lc
 * @email 389125111@qq.com
 * @create 2018-06-12 10:49
 */
public class ShiroAuthFilter extends AuthenticationFilter {
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if (!getSubject(request, response).isAuthenticated()) {
            onLoginFail(response);
            return false;
        } else {
            return true;
        }
    }

    private void onLoginFail(ServletResponse response) throws IOException {

        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setContentType("application/json;charset=UTF-8");
        httpResponse.setStatus(HttpServletResponse.SC_OK);
        Gson gson = new Gson();
        httpResponse.getWriter().write(gson.toJson(ResponseResult.unauthorizedError()));

    }
}
